package org.evil.deus.rss.widget;

import java.lang.ref.WeakReference;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

public class RSSWidgetUpdateService extends Service{
	
	public static final String EXTRA_APPWIDGETID = "extra_app_widget_id";
	
	private int [] appWidgetIds = null;
	private Thread updater = null;	
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		appWidgetIds = intent.getIntArrayExtra(EXTRA_APPWIDGETID);
		if (updater == null || !updater.isAlive()) {
			updater = new Thread(new Refresher(this, appWidgetIds));
			updater.start();
		}
		return super.onStartCommand(intent, flags, startId);
	}
	
	private class Refresher implements Runnable {
		private int [] appWidgetIds = null;
		private WeakReference<Context> reference = null;
		
		public Refresher(Context context, int [] ids) {
			reference = new WeakReference<Context>(context);
			appWidgetIds = ids;
		}
		
		public void run() {
			Context context = null;
			if (reference != null && (context = reference.get()) != null) {
				AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
				Thread thread = null;
				for (Integer id: appWidgetIds) {
					thread = new Thread(new Updater(appWidgetManager, id));
					thread.start();
					try {
						thread.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	private class Updater implements Runnable {
		
		private int appWidgetId;
		private AppWidgetManager appWidgetManager = null;
		
		public Updater(AppWidgetManager appWidgetManager, int id) {
			this.appWidgetManager = appWidgetManager;
			this.appWidgetId = id;
		}
		
		public void run() {
			// TODO
		}
	}
}
